/**
 * Copyright 2009-2011 xiaonei.com All right reserved.
 * This software is the confidential and proprietary information of Xiaonei.com ("Confidential Information"). 
 * You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with Xiaonei.com.
 * Create by XiaoNeiAntiSpamTeam
 *
 */

package com.xiaonei.testice.testicestorm.publisher;

import Ice.Communicator;
import Ice.ObjectPrx;
import IceStorm.NoSuchTopic;
import IceStorm.TopicExists;
import IceStorm.TopicManagerPrx;
import IceStorm.TopicManagerPrxHelper;
import IceStorm.TopicPrx;

import com.xiaonei.testice.testicestorm.HelloWorldPrx;
import com.xiaonei.testice.testicestorm.HelloWorldPrxHelper;
import com.xiaonei.testice.util.IceUtil;

/**
 * @ClassName: HelloWorldPublisher
 * @Description: HelloWord消息的发布者
 * @author shaohui.liu shaohui.liu@opi-corp.com
 * @date Feb 1, 2010 6:37:34 PM
 * 
 */
public class HelloWorldPublisher {

    private HelloWorldPrx helloWorldPrx = null;

    public static HelloWorldPublisher instance = new HelloWorldPublisher();

    public static HelloWorldPublisher getInstance() {
        return instance;
    }

    public HelloWorldPublisher() {
        try {
            helloWorldPrx = getHelloWorldPrx();
        } catch (TopicExists e) {
            System.err.println("helloWorldPrx is null");
            helloWorldPrx = null;
        }
    }

    private HelloWorldPrx getHelloWorldPrx() throws TopicExists {
        Communicator co = Ice.Util.initialize(IceUtil.initData());
        ObjectPrx objectPrx = co.stringToProxy("TopicManager.Proxy");
        TopicManagerPrx topicManagerPrx = TopicManagerPrxHelper.checkedCast(objectPrx);
        TopicPrx topicPrx = null;
        try {
            topicPrx = topicManagerPrx.retrieve("HelloWorld");
        } catch (NoSuchTopic ex) {
            topicPrx = topicManagerPrx.create("HelloWorld");
        }
        ObjectPrx pub = topicPrx.getPublisher().ice_oneway();
        HelloWorldPrx helloWorldPrx = HelloWorldPrxHelper.uncheckedCast(pub);
        return helloWorldPrx;
    }

    public void say(String message) {
        if (helloWorldPrx == null) {
            try {
                helloWorldPrx = getHelloWorldPrx();
            } catch (TopicExists e) {
                System.err.println("helloWorldPrx is null");
                return;
            }
        }
        helloWorldPrx.say(message);
    }

    public static void main(String[] args) {
        HelloWorldPublisher.getInstance().say("hello world!");
    }
}
